<?php

namespace app\admin\controller\kf;

use addons\fastchat\library\Chat;
use addons\fastchat\library\Common;
use app\admin\model\lists\One;
use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 客服记录
 *
 * @icon fa fa-circle-o
 */
class Record extends Backend
{

    /**
     * Record模型对象
     * @var \app\admin\model\kf\Record
     */
    protected $model = null;
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kf\Record;
        $admin = $this->auth->getUserInfo();

        $this->assign('admin',$admin);
        $rule = Db::name('auth_group_access')->alias('a')->join('auth_group b','a.group_id = b.id')->where('a.uid',$admin['id'])->field('b.rules,a.group_id')->find();
        $rules = $rule['rules'];
        if($rules == '*'){
            $rules = Db::name('auth_rule')->column('id');
        }else{
            $rules = explode(',',$rule['rules']);
        }
        $this->rule = $rules;
        $this->assignconfig('rule', $rules);
        $this->assign('rules', $rules);

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function search()
    {
        return $this->view->fetch();
    }

    /**
     * 查询是否存在记录
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function chaxun(){
        $params = $this->request->post('');
        $where = [];
        if($params['car_num']){
            $where['car_num'] = $params['car_num'];
        }
        if($params['phone']){
            $where['phone'] = $params['phone'];
        }
        if($params['car_vin']){
            $where['car_vin'] = $params['car_vin'];
        }
        if($params['car_engine']){
            $where['car_engine'] = $params['car_engine'];
        }
        if(!$where) $this->error('至少填写一项');
        $info = Db::name('kf_record')->where($where)->where('deletetime',)->find();
        if(isset($where['phone'])) unset($where['phone']);
        $one_info = Db::name('list_one')->where($where)->whereNotIn('status',[6,7])->where('plan_strattime','<',time())->where('plan_endtime','>',time())->field('id,yw_class,yw_belonger,tong_number,car_vin,car_engine')->order('status desc,id asc')->find();
        if(!$info){
            if($one_info){
                $re_info = Db::name('kf_record')->where('one_id',$one_info['id'])->find();
                if($re_info) {
                    $this->handle_update_one_id($one_info, $re_info);
                    $id = $re_info['id'];
                }else{
                    $id = $this->handle_add_one_id($params,$one_info);
                }
            }else{
                $id = $this->handle_add_one_id($params);
            }
        }else{
            $this->handle_update_one_id($one_info,$info);
            $id = $info['id'];
        }
        $this->success('','',['id'=>$id]);
    }

    /**
     * 修改附属服务单id
     * @param $one_info
     * @param $info
     * @return void
     * @throws PDOException
     * @throws \think\Exception
     */
    public function handle_update_one_id($one_info,$info){
        if($one_info && $one_info['id'] != $info['one_id']){
            $data['yw_class'] = $one_info['yw_class'];
            $data['yw_belonger'] = $one_info['yw_belonger'];
            $data['tong_number'] = $one_info['tong_number'];
            $data['one_id'] = $one_info['id'];
            $data['car_vin'] = $one_info['car_vin'];
            $data['car_engine'] = $one_info['car_engine'];
            Db::name('kf_record')->where('id',$info['id'])->update($data);
        }
    }

    /**
     * 添加新得客服记录
     * @return void
     */
    public function handle_add_one_id($params,$one_info = []){
        $data['car_num'] = $params['car_num'];
        $data['phone'] = $params['phone'];
        $data['car_vin'] = $params['car_vin'];
        $data['car_engine'] = $params['car_engine'];
        $data['createtime'] = time();
        $data['updatetime'] = time();
        if($one_info){
            $data['yw_class'] = $one_info['yw_class'];
            $data['yw_belonger'] = $one_info['yw_belonger'];
            $data['tong_number'] = $one_info['tong_number'];
            $data['one_id'] = $one_info['id'];
            $data['car_vin'] = $one_info['car_vin'];
            $data['car_engine'] = $one_info['car_engine'];
        }
        $id = Db::name('kf_record')->insertGetId($data);
        return $id;
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add($ids = null)
    {
        if (false === $this->request->isPost()) {
            $params = $this->request->get('');
            if(isset($params['id']) && $params['id']){
                $id = $params['id'];
            }else{
                $id = $ids;
            }
            if(!$id) $this->error('参数错误');
            $res = Db::name('kf_record')->where('id',$id)->find();
            if($res['car_num']){
                $row = Db::name('kf_record_list')->alias('a')->join('kf_record b','a.rid = b.id')->where('b.car_num',$res['car_num'])->where('a.deletetime',)->where('b.deletetime',)->order('a.id asc')->field('a.*,b.car_num')->select();
            }else{
                $row = Db::name('kf_record_list')->where('rid',$id)->where('deletetime',)->order('id asc')->select();
            }
            foreach ($row as &$v){
                $v['type'] = $this->get_type()[$v['type']];
                $v['ld_type'] = $v['ld_type'] == 1 ? '本人' : '他人';
                $v['fenpei'] = $v['fenpei'] ? Db::name('admin')->where('id',$v['fenpei'])->value('username') : '';
                $v['buchang_img'] = $v['buchang_img'] ? explode(',',$v['buchang_img']) : [];
            }

            $this->view->assign('res',$res);
            $this->view->assign('row',$row);
            $admin = $this->auth->getUserInfo();
            $cateid = $admin['zuzhi'];
            $date = db('zuzhi')->where('delete_id',0)->select();
            $arr = $this->frontdels($date,$cateid);
            $arr[] = (int)$cateid;
            $fenpei = Db::name('admin')
                ->alias('a')
                ->join("auth_group_access b", "a.id = b.uid")
                ->where('a.zuzhi','in',$arr)
                ->where('b.group_id', 10)
                ->field('a.username,a.id')->select();
            $this->view->assign('fenpei',$fenpei);
            return $this->view->fetch();
        }
    }

    /**
     * 保存客服记录
     * @return void
     */
    public function save_list(){
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if(!$params['type']) $this->error('请选择类别');
        if(!$params['content']) $this->error('请输入备注内容');
        $admin = $this->auth->getUserInfo();
        $row = $this->model->get(['id'=>$params['rid']]);
        $result = false;
        $id = 0;
        Db::startTrans();
        try {
            if(isset($params['id']) && $params['id']){
                $data['type'] = $params['type'];
                $data['date'] = $params['date'];
                $data['content'] = $params['content'];
                $data['fenpei'] = $params['fenpei'];
                $data['phone'] = $params['phone'];
                $data['name'] = $params['name'];
                $data['ld_type'] = $params['ld_type'];
                $data['chexing'] = $params['chexing'];
                $data['updatetime'] = time();
                $result = Db::name('kf_record_list')->where('id',$params['id'])->update($data);
                $ids = $params['id'];
            }else{
                $data['type'] = $params['type'];
                $data['date'] = $params['date'];
                $data['content'] = $params['content'];
                $data['user_id'] = $params['user_id'];
                $data['user_name'] = $params['user_name'];
                $data['rid'] = $params['rid'];
                $data['fenpei'] = $params['fenpei'];
                $data['phone'] = $params['phone'];
                $data['name'] = $params['name'];
                $data['ld_type'] = $params['ld_type'];
                $data['chexing'] = $params['chexing'];
                $data['createtime'] = time();
                $data['updatetime'] = time();
                $result = Db::name('kf_record_list')->insertGetId($data);
                $id = $result;
                $ids = $id;
            }
            if($data['fenpei']){
                $admin = $this->auth->getUserInfo();
                Chat::init(1)
                    ->admin($params['fenpei'])
                    ->send($params,$ids,$admin);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $info = Db::name('kf_record_list')->where('id',$ids)->find();
        $info['type'] = $this->get_type()[$info['type']];
        $info['ld_type'] = $info['ld_type'] == 1 ? '本人' : '他人';
        $info['fenpei'] = $info['fenpei'] ? Db::name('admin')->where('id',$info['fenpei'])->value('username') : '';
        $info['buchang_img'] = $info['buchang_img'] ? explode(',',$info['buchang_img']) : [];
        $this->success('','',$info);
    }

    public function tan(){
        $id = $_GET['id'];
        $info = Db::name('kf_record')->where('id',$id)->find();
        $info['learned_name'] = '';
        if($info['one_id']){
            $info['learned_name'] = Db::name('list_one')->where('id',$info['one_id'])->value('learned_name');
        }
        $this->view->assign('info',$info);
        $site = Config::get('site');
        $this->view->assign('chexing',$site['chexing']);
        $admin = $this->auth->getUserInfo();
        $this->view->assign('admin',$admin);
        $cateid = $admin['zuzhi'];
        $date = db('zuzhi')->where('delete_id',0)->select();
        $arr = $this->frontdels($date,$cateid);
        $arr[] = (int)$cateid;
        $fenpei = Db::name('admin')
            ->alias('a')
            ->join("auth_group_access b", "a.id = b.uid")
            ->where('a.zuzhi','in',$arr)
            ->where('b.group_id', 10)
            ->field('a.username,a.id')->select();
        $this->view->assign('fenpei',$fenpei);
        return $this->fetch();
    }
    public function frontdels($data,$cateid){
        //var_dump($data);die();
        static $arr=array();
        foreach ($data as $key => $v) {
            if($v["pid"]==$cateid){
                $arr[]=$v['id'];
                $this->frontdels($data,$v['id']);
            }
        }
        return $arr;
    }

    public function get_type(){
        return ['1'=>'报案','2'=>'咨询','3'=>'退费','4'=>'销案退费','5'=>'客服催办','6'=>'投诉','7'=>'工商投诉','8'=>'公众号投诉','9'=>'支付投诉','10'=>'渠道催办','11'=>'舆情处理'];
    }
    public function edit_tan(){
        $id = $_GET['id'];
        $row = Db::name('kf_record_list')->where('id',$id)->find();
        $this->view->assign('row',$row);
        $info = Db::name('kf_record')->where('id',$row['rid'])->find();
        $info['learned_name'] = '';
        if($info['one_id']){
            $info['learned_name'] = Db::name('list_one')->where('id',$info['one_id'])->value('learned_name');
        }
        $this->view->assign('info',$info);
        $site = Config::get('site');
        $this->view->assign('chexing',$site['chexing']);
        $admin = $this->auth->getUserInfo();
        $cateid = $admin['zuzhi'];
        $date = db('zuzhi')->where('delete_id',0)->select();
        $arr = $this->frontdels($date,$cateid);
        $arr[] = (int)$cateid;
        $fenpei = Db::name('admin')
            ->alias('a')
            ->join("auth_group_access b", "a.id = b.uid")
            ->where('a.zuzhi','in',$arr)
            ->where('b.group_id', 10)
            ->field('a.username,a.id')->select();
        $this->view->assign('fenpei',$fenpei);
        return $this->fetch();
    }

    /**
     * 服务单信息
     * @param $ids
     * @return string|\think\response\Json
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function fuwudan($ids = null)
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        $id = $this->request->get('id');
        $row = $this->model->get(['id'=>$id]);
        $this->view->assign('row', $row);
        if ($this->request->isAjax()) {
            $this->model = new One();
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(["zuzhi"])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $v) {
                $v['sign'] = 0;
                $sign = Db::name('sign')->where('orderid',$v['id'])->find();
                if($sign){
                    $v['sign'] = 1;
                }
            }
            $all_main_free =  Db::name('list_one')
                ->alias('one')
                ->join('zuzhi zuzhi','one.yw_class = zuzhi.id','left')
                ->where($where)
                ->group('one.id')->where('deletetime',)
                ->field('one.main_free,one.main_sum')
                ->select(false);
            $all = Db::query('select sum(c.main_free) as all_main_free,sum(c.main_sum) as all_main_sum from ('.$all_main_free.') as c');
            $all_main_free = round($all[0]['all_main_free'],2);
            $all_main_sum = round($all[0]['all_main_sum'],2);
            $result = array("total" => $list->total(), "rows" => $list->items(),'all_main_free'=>$all_main_free,'all_main_sum'=>$all_main_sum);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 浏览
     * @param $ids
     * @return void
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onedetails($ids = null){
        $this->model = new One();
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $admin = $this->auth->getUserInfo();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $row['car_register'] = date('Y-m-d',$row['car_register']);
        $row['plan_strattime'] = date('Y-m-d H:i:s',$row['plan_strattime']);
        $row['plan_endtime'] = date('Y-m-d H:i:s',$row['plan_endtime']);
        $this->view->assign('row', $row);
        $select = selectMenus_zuzhi($admin['zuzhi']);
        $this->assign('selectMenu',$select);
        $ren = db('admin')->where('zuzhi','in',$row['yw_class'])->select();
        $this->assign('ren',$ren);
        $ying = db('tong_files')->where('tong_id',$ids)->select();
        $this->assign('file', $ying);

        $yijian = db('yijian')->where('did',$ids)->select();
        $this->assign('yijian',$yijian);
        return $this->view->fetch();
    }
}
